<?php

namespace app\admin\controller\community\config;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\community\project\Settimeslot as SettimeslotModel;

/**
 * 时间关联配置管理
 *
 * @icon fa fa-calendar
 */
class Timeslot extends Backend
{
    /**
     * Timeslot模型对象
     * @var \app\admin\model\community\config\Timeslot
     */
    protected $model = null;

    /**
     * 是否开启数据限制
     * @var bool
     */
    protected $dataLimit = false;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\community\config\Timeslot;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $searchFields = ['id', 'code', 'name', 'remark'];
            $sortFields = ['id', 'code', 'name', 'day', 'start_time', 'end_time', 'community_id', 'publicwelfare_id', 'timezone_id', 'status', 'weigh', 'createtime', 'updatetime'];

            list($where, $sort, $order, $offset, $limit) = $this->buildparams($sortFields, $searchFields);
            $where = [];
            // 获取URL中传递的参数
            $community_id = $this->request->param('community_id', 0);
            $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
            $timezone_id = $this->request->param('timezone_id', 0);

            // 如果有传递参数，则添加到查询条件中
            if ($community_id > 0) {
                $where['fa_community_timeslot_config.community_id'] = $community_id;
            }
            if ($publicwelfare_id > 0) {
                $where['fa_community_timeslot_config.publicwelfare_id'] = $publicwelfare_id;
            }
            if ($timezone_id > 0) {
                $where['fa_community_timeslot_config.timezone_id'] = $timezone_id;
            }

            $list = $this->model
                ->with(['community', 'publicwelfare', 'timezone'])
                ->where($where)
                ->field('fa_community_timeslot_config.*,community.name as community_name,publicwelfare.project_name as publicwelfare_name,timezone.name as timezone_name')
                ->order($sort, $order)
                ->paginate($limit);
                
            // 处理列表数据，移除时间中的秒数部分
            $items = $list->items();
            
            // 按条件分组重新排序code字段
            $groupedItems = [];
            foreach ($items as $item) {
                $groupKey = $item['community_id'] . '_' . $item['publicwelfare_id'] . '_' . $item['timezone_id'];
                if (!isset($groupedItems[$groupKey])) {
                    $groupedItems[$groupKey] = [];
                }
                $groupedItems[$groupKey][] = $item;
            }
            
            // 对每个分组按开始时间排序并重新编号code
            foreach ($groupedItems as $groupKey => $groupItems) {
                // 按开始时间排序
                usort($groupItems, function($a, $b) {
                    return strcmp($a['start_time'], $b['start_time']);
                });
                
                // 重新编号并更新数据库
                foreach ($groupItems as $index => $item) {
                    $newCode = '时段' . ($index + 1);
                    if ($item['code'] !== $newCode) {
                        // 更新数据库中的code字段
                        $this->model->where('id', $item['id'])->update(['code' => $newCode]);
                        // 更新当前项的code用于显示
                        $item['code'] = $newCode;
                    }
                }
                
                // 更新分组数据
                $groupedItems[$groupKey] = $groupItems;
            }
            
            // 重新组合所有项目
            $updatedItems = [];
            foreach ($groupedItems as $groupItems) {
                $updatedItems = array_merge($updatedItems, $groupItems);
            }
            
            foreach ($updatedItems as &$item) {
                // 处理开始时间
                if (isset($item['start_time']) && preg_match('/^\d{2}:\d{2}:\d{2}$/', $item['start_time'])) {
                    $item['start_time'] = substr($item['start_time'], 0, 5);
                }
                // 处理结束时间
                if (isset($item['end_time']) && preg_match('/^\d{2}:\d{2}:\d{2}$/', $item['end_time'])) {
                    $item['end_time'] = substr($item['end_time'], 0, 5);
                }
            }
            unset($item); // 释放引用
            
            $result = ['total' => $list->total(), 'rows' => $updatedItems];
            return json($result);
        }

        // 获取URL中传递的参数并传递给视图
        $community_id = $this->request->param('community_id', 0);
        $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
        $timezone_id = $this->request->param('timezone_id', 0);
        $this->view->assign('community_id', $community_id);
        $this->view->assign('publicwelfare_id', $publicwelfare_id);
        $this->view->assign('timezone_id', $timezone_id);

        // 如果通过网址传入了community_id和publicwelfare_id，则设置一个标记，用于控制视图中的字段显示
        $simplifiedView = ($community_id > 0 || $publicwelfare_id > 0);
        $this->view->assign('simplifiedView', $simplifiedView);

        // 自动生成时段代码
        if ($community_id > 0 && $publicwelfare_id > 0) {
            $code = $this->reorderTimeslotCodes($community_id, $publicwelfare_id, $timezone_id);
            $this->view->assign('code', $code);
        } else {
            $this->view->assign('code', ''); // 设置默认空值
        }

        return $this->view->fetch();
    }

    /**
     * 自动生成时段代码
     * @param int $community_id 社区ID
     * @param int $publicwelfare_id 公益项目ID
     * @param int $timezone_id 时区ID
     * @return string 生成的时段代码
     */
    protected function generateTimeslotCode($community_id, $publicwelfare_id, $timezone_id)
    {
        // 获取当前条件下已有的时段数量
        $count = $this->model
            ->where('community_id', $community_id)
            ->where('publicwelfare_id', $publicwelfare_id)
            ->where('timezone_id', $timezone_id)
            ->count();

        // 生成新的时段代码
        return '时段' . ($count + 1);
    }

    /**
     * 重新排序时段代码
     * @param int $community_id 社区ID
     * @param int $publicwelfare_id 公益项目ID
     * @param int $timezone_id 时区ID
     * @return string 返回新的时段代码
     */
    protected function reorderTimeslotCodes($community_id, $publicwelfare_id, $timezone_id)
    {
        // 获取所有符合条件的时段记录
        $timezone_id = $timezone_id ?: 1;
        $timeslots = $this->model
            ->where('community_id', $community_id)
            ->where('publicwelfare_id', $publicwelfare_id)
            ->where('timezone_id', $timezone_id)
            ->order('start_time asc')
            ->select();

        // 重新编号
        foreach ($timeslots as $key => $timeslot) {
            $timeslot->save(['code' => '时段' . ($key + 1)]);
        }
        // 返回一个新的时段代码
        return '时段' . (count($timeslots) + 1);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                // 设置默认宽度为5
                if (!isset($params['weigh']) || empty($params['weigh'])) {
                    $params['weigh'] = 5;
                }

                // 设置创建时间和更新时间为当前时间
                $currentTime = time();
                $params['createtime'] = $currentTime;
                $params['updatetime'] = $currentTime;

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                // 从URL参数中获取community_id、publicwelfare_id和timezone_id
                $community_id = $this->request->param('community_id', 0);
                $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
                $timezone_id = $this->request->param('timezone_id', 0);

                // 如果表单没有提交这些值，但URL中有，则自动填充
                if (!isset($params['community_id']) && $community_id > 0) {
                    $params['community_id'] = $community_id;
                }
                if (!isset($params['publicwelfare_id']) && $publicwelfare_id > 0) {
                    $params['publicwelfare_id'] = $publicwelfare_id;
                }
                if (!isset($params['timezone_id']) && $timezone_id > 0) {
                    $params['timezone_id'] = $timezone_id;
                }

                // 处理 day 字段
                $params['day'] = array_map(function($item) {
                    return preg_replace("/\"|\\\\/", "", $item ?? "");
                }, $params['day'] ?? []);
                $params['day'] = join(",", $params['day']);

                // 处理开始时间和结束时间，移除秒数
                if (isset($params['start_time']) && preg_match('/^\d{2}:\d{2}:\d{2}$/', $params['start_time'])) {
                    $params['start_time'] = substr($params['start_time'], 0, 5);
                }
                if (isset($params['end_time']) && preg_match('/^\d{2}:\d{2}:\d{2}$/', $params['end_time'])) {
                    $params['end_time'] = substr($params['end_time'], 0, 5);
                }

                // 自动生成时段代码
                if (isset($params['community_id']) && isset($params['publicwelfare_id']) && isset($params['timezone_id'])) {
                    $params['code'] = $this->generateTimeslotCode($params['community_id'], $params['publicwelfare_id'], $params['timezone_id']);
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    // 添加成功后重新排序时段代码
                    $community_id = $params['community_id'] ?? 0;
                    $publicwelfare_id = $params['publicwelfare_id'] ?? 0;
                    $timezone_id = $params['timezone_id'] ?? 0;

                    if ($community_id > 0 && $publicwelfare_id > 0 && $timezone_id > 0) {
                        $this->reorderTimeslotCodes($community_id, $publicwelfare_id, $timezone_id);
                    }

                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 获取社区列表
        $communityList = \app\admin\model\Community::where('status', 1)->column('name', 'id');
        $this->view->assign('communityList', $communityList);

        // 获取公益项目列表
        $publicwelfareList = \app\admin\model\community\Publicwelfare::where('status', 1)->column('project_name', 'id');
        $this->view->assign('publicwelfareList', $publicwelfareList);

        // 获取时区列表
        $timezoneList = \app\admin\model\community\config\Timezone::where('status', 1)->column('name', 'id');
        $this->view->assign('timezoneList', $timezoneList);

        // 获取当前用户所属社区和URL参数
        $user = $this->auth->getUserInfo();
        $community_id = $this->request->param('community_id', $user['community_id'] ?? 0);
        $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
        $timezone_id = $this->request->param('timezone_id', 0);
        $this->view->assign('community_id', $community_id);
        $this->view->assign('publicwelfare_id', $publicwelfare_id);
        $this->view->assign('timezone_id', $timezone_id);

        // 查询未被选取的时间槽列表
        $latestRecord = $this->model
            ->where('status', 1)
            ->order('createtime desc')
            ->find();

        $defaultDay = $latestRecord ? $latestRecord['day'] : '';
        $this->view->assign('defaultDay', $defaultDay);

        if ($community_id > 0 && $publicwelfare_id > 0 && $timezone_id > 0) {
            $existingNames = $this->model
                ->where('community_id', $community_id)
                ->where('publicwelfare_id', $publicwelfare_id)
                ->where('timezone_id', $timezone_id)
                ->column('name');

            $allTimeslots = SettimeslotModel::where('community_id', $community_id)
                ->where('publicwelfare_id', $publicwelfare_id)
                ->where('timezone_id', $timezone_id)
                ->select();

            $timeslotList = [];
            foreach ($allTimeslots as $timeslot) {
                $timeslotName = $timeslot['timeslot_name'] ?? $timeslot['id'];
                if (!in_array($timeslotName, $existingNames)) {
                    $timeslotList[$timeslotName] = $timeslotName;
                }
            }
            $this->view->assign('timeslotList', $timeslotList);
        }

        // 视图变量
        $simplifiedView = ($community_id > 0 || $publicwelfare_id > 0);
        $this->view->assign('simplifiedView', $simplifiedView);
        $timezone_id = 1;
        if ($community_id > 0 && $publicwelfare_id > 0) {
            $code = $this->reorderTimeslotCodes($community_id, $publicwelfare_id, $timezone_id);
            $this->view->assign('code', $code);
        } else {
            $this->view->assign('code', '');
        }

        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = null)
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        try {
            $records = $this->model->where('id', 'in', $ids)->select();
            $communityTimezoneMap = [];

            foreach ($records as $record) {
                $key = $record['community_id'] . '-' . $record['publicwelfare_id'] . '-' . $record['timezone_id'];
                $communityTimezoneMap[$key] = [
                    'community_id' => $record['community_id'],
                    'publicwelfare_id' => $record['publicwelfare_id'],
                    'timezone_id' => $record['timezone_id']
                ];
            }

            $result = $this->model->where('id', 'in', $ids)->delete();

            if ($result) {
                foreach ($communityTimezoneMap as $info) {
                    $this->reorderTimeslotCodes($info['community_id'], $info['publicwelfare_id'], $info['timezone_id']);
                }

                return json(['code' => 1, 'msg' => __('Delete successful')]);
            } else {
                $this->error(__('No rows were deleted'));
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        // 获取最近的记录的day值（不包括当前记录）
        $latestRecord = $this->model
            ->where('status', 1)
            ->where('id', '<>', $ids)
            ->order('createtime desc')
            ->find();

        if ($latestRecord && empty($row['day'])) {
            $row['day'] = $latestRecord['day'];
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                // 处理 day 字段
                if (isset($params['day'])) {
                    $params['day'] = array_map(function($item) {
                        return preg_replace("/\"|\\\\/", "", $item ?? "");
                    }, $params['day'] ?? []);
                    $params['day'] = join(",", $params['day']);
                }

                // 处理开始时间和结束时间，移除秒数
                if (isset($params['start_time']) && preg_match('/^\d{2}:\d{2}:\d{2}$/', $params['start_time'])) {
                    $params['start_time'] = substr($params['start_time'], 0, 5);
                }
                if (isset($params['end_time']) && preg_match('/^\d{2}:\d{2}:\d{2}$/', $params['end_time'])) {
                    $params['end_time'] = substr($params['end_time'], 0, 5);
                }

                $result = false;
                Db::startTrans();
                try {
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                if ($result !== false) {
                    $community_id = $params['community_id'] ?? $row['community_id'];
                    $publicwelfare_id = $params['publicwelfare_id'] ?? $row['publicwelfare_id'];
                    $timezone_id = $params['timezone_id'] ?? $row['timezone_id'];

                    if ($community_id > 0 && $publicwelfare_id > 0 && $timezone_id > 0) {
                        $this->reorderTimeslotCodes($community_id, $publicwelfare_id, $timezone_id);
                    }

                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 获取社区列表
        $communityList = \app\admin\model\Community::where('status', 1)->column('name', 'id');
        $this->view->assign('communityList', $communityList);

        // 获取公益项目列表
        $publicwelfareList = \app\admin\model\community\Publicwelfare::where('status', 1)->column('project_name', 'id');
        $this->view->assign('publicwelfareList', $publicwelfareList);

        // 获取时区列表
        $timezoneList = \app\admin\model\community\config\Timezone::where('status', 1)->column('name', 'id');
        $this->view->assign('timezoneList', $timezoneList);

        // 获取URL参数和当前用户所属社区
        $user = $this->auth->getUserInfo();
        $community_id = $this->request->param('community_id', $user['community_id'] ?? 0);
        $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
        $timezone_id = $this->request->param('timezone_id', 0);
        $this->view->assign('community_id', $community_id);
        $this->view->assign('publicwelfare_id', $publicwelfare_id);
        $this->view->assign('timezone_id', $timezone_id);

        // 视图变量
        $simplifiedView = ($community_id > 0 || $publicwelfare_id > 0);
        $this->view->assign('simplifiedView', $simplifiedView);
        $this->view->assign('code', $row['code']);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
